package cn.cheqi.recovery.api.controller;


import cn.cheqi.recovery.api.dto.DataGridView;
import cn.cheqi.recovery.api.entity.Order;
import cn.cheqi.recovery.api.entity.User;
import cn.cheqi.recovery.api.mapper.UserMapper;
import cn.cheqi.recovery.api.service.OrderService;
import cn.cheqi.recovery.api.service.UserService;
import cn.cheqi.recovery.api.upload.UploadService;
import cn.cheqi.recovery.api.utils.MD5Util;
import cn.cheqi.recovery.api.utils.SysFileUtil;
import cn.cheqi.recovery.api.vo.OrderVO;
import cn.cheqi.recovery.api.vo.UserVO;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  api接口已入驻业主前端控制器
 * </p>
 *
 * @author Robin
 * @since 2020-02-23
 */
@RestController("apiUserController")
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UploadService uploadService;

    //保存到阿里云的文件夹位置
    @Value("${aliyun.oss.UserSave}")
    private String UserSave;

    /**
     * api接口加载所有已入驻业主
     * @param userVO
     * @return
     */
    @RequestMapping("/loadAllUsers")
    public DataGridView toLoadAllUsers(UserVO userVO){
        IPage<User> page = new Page<>(userVO.getPage(),userVO.getLimit());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //获取查询体内的用户ID
        Long userId = userVO.getUserId();
        //获取查询体内的业主姓名
        String userName = userVO.getUserName();
        //获取查询体内的业主联系方式
        String userPhone = userVO.getUserPhone();
        //判断这三个条件是否为空,若不是则加进查询条件
        if (userId != null){
            wrapper.like("user_id",userId);
        }
        //模糊查询业主姓名
        if (!StringUtils.isBlank(userName)){
            //去掉字符串中的空格
            String nameTrim = userName.replace(" ", "");
            wrapper.like(nameTrim != null,"user_name",nameTrim);
        }
        //模糊查询业主联系方式
        if (!StringUtils.isBlank(userPhone)){
            //去掉字符串中的空格
            String phoneTrim = userPhone.replace(" ", "");
            wrapper.like(phoneTrim != null,"user_phone",phoneTrim);
        }
        //通过id列倒序输出sql结果
        wrapper.orderByDesc("user_id");
        userService.page(page,wrapper);
        //DTO传输对象
        DataGridView dataGridView = new DataGridView();
        dataGridView.setCode(0);
        dataGridView.setMsg("");
        Map<Object,Object> map = new HashMap<>();
        map.put("count",page.getRecords().size());
        map.put("page",page.getCurrent());
        map.put("zpage",page.getPages());
        map.put("list",page.getRecords());
        dataGridView.setData(map);
        return dataGridView;
    }


    /**
     * 通过用户ID获取用户信息
     * @param userVO
     * @return
     */
    @PostMapping("/getUserById")
    public DataGridView getUserById(UserVO userVO){
        //判断用户是否存在
        User user = userService.getById(userVO.getUserId());
        if (user == null){
            return new DataGridView(1,"该用户不存在","");
        }else {
            return new DataGridView(0,"",user);
        }
    }


    /**
     * api接口添加用户
     * @param userVO
     * @return
     */
    @PostMapping("/addUser")
    @Transactional
    public DataGridView addUser(UserVO userVO){
        //判断手机号是否已被注册
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone",userVO.getUserPhone());
        //如果查询得出的条数大于0,则该手机号已被注册
        if (userService.count(wrapper) > 0){
            return new DataGridView(1,"该手机号已被注册","");
        }
        try{
            //设置默认的图片路径
            userVO.setUserPic("https://rob1n-bucket.oss-cn-shenzhen.aliyuncs.com/recovery/user/default/default.jpg");
            userService.save(userVO);
            return new DataGridView(0,"添加成功",null);
        } catch (Exception e){
            e.printStackTrace();
            return new DataGridView(-1,"添加失败",null);
        }
    }

    /**
     * api接口通过用户ID删除用户
     * @param userVO
     * @return
     */
    @PostMapping("/deleteUserById")
    @Transactional
    public DataGridView deleteUserById(UserVO userVO){
        //判断用户是否存在
        User user = userService.getById(userVO.getUserId());
        if (user == null){
            return new DataGridView(1,"该用户不存在","");
        }
        //如果存在的话则进行接下来的步骤
        try{
            userService.removeById(userVO.getUserId());
            return new DataGridView(0,"删除成功",null);
        }catch (Exception e){
            e.printStackTrace();
            return new DataGridView(-1,"删除失败",null);
        }
    }

    /**
     * api接口通过用户ID修改用户
     * @param userVO
     * @return
     */
    @PostMapping("/editUser")
    @Transactional
    public DataGridView editUserById(UserVO userVO){
        //判断该用户是否存在
        User user = userService.getById(userVO.getUserId());
        if (user == null){
            return new DataGridView(1,"您所编辑的用户不存在","");
        }
        //判断编辑信息是否为空
        if (userVO.getAccumulatedPoints()==null&&userVO.getAreaAddress()==null&&userVO.getAvailablePoints()==null&&userVO.getCommunityId()==null&&
            userVO.getCommunityName()==null&&userVO.getDetailedAddress()==null&&userVO.getFloorUnit()==null&&userVO.getRegisterTime()==null&&
            userVO.getUserAge()==null&&userVO.getUserName()==null&&userVO.getUserPassword()==null&&userVO.getUserPhone()==null){
            return new DataGridView(1,"您所输入的编辑信息不能为空","");
        }
        try{
            userService.updateById(userVO);
            return new DataGridView(0,"修改成功",null);
        }catch (Exception e){
            e.printStackTrace();
            return new DataGridView(0,"修改成功",null);
        }
    }


    /**
     * 通过用户ID更新用户的头像
     * @param userVO
     * @param file 上传的用户头像
     * @return
     */
    @PostMapping("/editUserPicById")
    @Transactional
    public DataGridView editUserPicById(@RequestParam("file")MultipartFile file, UserVO userVO){
        //判断该用户是否存在
        User user = userService.getById(userVO.getUserId());

        if (user == null){
            return new DataGridView(1,"您所编辑的用户不存在","");
        }

        //如果满足上述条件则更新头像
        try{
            DataGridView dataGridView = uploadService.uploadImg(file,UserSave);
            //判断回显的data是否为空,为空的话则不管,否则更新图片
            if (dataGridView.getData() != null && dataGridView.getData() != ""){
                userVO.setUserPic((String) dataGridView.getData());
                userService.updateById(userVO);
            }
            return dataGridView;
        }catch (Exception e){
            e.printStackTrace();
            return new DataGridView(1,"头像更新失败","");
        }
    }

    /**
     * 添加用户的身份证验证图片接口
     * @param file 上传的身份证照片
     * @return
     */
    @PostMapping("/uploadUserIdentityPic")
    @Transactional
    public DataGridView uploadUserIdentityPic(@RequestParam("identityPic")MultipartFile file){
        try{
            DataGridView dataGridView = uploadService.uploadImg(file,UserSave);
            return dataGridView;
        }catch (Exception e){
            e.printStackTrace();
            return new DataGridView(1,"身份证图片上传失败","");
        }
    }


    /**
     * 把上传好的身份证图片以及身份证号和真实姓名绑定用户ID更新提交用户信息
     * @param userVO
     * @return
     */
    @PostMapping("/addUserIdentityPic")
    @Transactional
    public DataGridView addUserIdentityPic(UserVO userVO){
        //判断该用户是否存在
        User user = userService.getById(userVO.getUserId());
        if (user == null){
            return new DataGridView(1,"您所编辑的用户不存在","");
        }
        //取出每个用户身份证的照片链接
        String identityPic = userVO.getIdentityPic();
        if (identityPic.equals("")){
            return new DataGridView(1,"请先上传图片","");
        }
        //如果满足上述条件则提交身份证照片到数据库
        try{
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id",userVO.getUserId());
            User updateUser = new User();
            updateUser.setIdentityPic(identityPic);
            //实名验证的真实姓名
            updateUser.setIdentityName(userVO.getIdentityName());
            //实名验证的身份证号
            updateUser.setIdentityNum(userVO.getIdentityNum());
            userService.update(updateUser,updateWrapper);
            return new DataGridView(0,"提交成功","");
        }catch (Exception e){
            e.printStackTrace();
            return new DataGridView(1,"提交失败","");
        }
    }

    /**
     * 通过业主ID获取业主实名验证的信息
     * @param userId
     * @return
     */
    @PostMapping("/getUserIdentityInfo")
    @Transactional
    public DataGridView getUserIdentityInfo(Long userId){
        User user = userService.getById(userId);
        if (user == null){
            return new DataGridView(1,"该用户信息不存在","");
        }
        try {
            User userInfo = new User();
            userInfo.setIdentityName(user.getIdentityName());
            userInfo.setIdentityNum(user.getIdentityNum());
            userInfo.setIdentityPic(user.getIdentityPic());
            userInfo.setIdentityStatus(user.getIdentityStatus());
            DataGridView dataGridView = new DataGridView();
            dataGridView.setCode(0);
            dataGridView.setMsg("");
            dataGridView.setData(userInfo);
            return dataGridView;
        } catch (Exception e) {
            e.printStackTrace();
            return new DataGridView(1,"查取信息出现错误","");
        }
    }


    /**
     * api接口通过用户ID查看该用户的所有订单详情
     * @param userVO
     * @return
     */
    @PostMapping("/findOrdersByUserId")
    public DataGridView findOrdersByUserId(UserVO userVO){
        //判断该用户是否存在
        User user = userService.getById(userVO.getUserId());
        if (user == null){
            return new DataGridView(1,"您所编辑的用户不存在","");
        }
        //分页条件
        Page<User> page = new Page<>();
        if (userVO.getPage() != null && userVO.getLimit() != null){
            page.setCurrent(userVO.getPage());
            page.setSize(userVO.getLimit());
        }
        List<OrderVO> orderVOS = userMapper.findOrdersByUserId(userVO.getUserId(),page);
        //DTO传输对象
        DataGridView dataGridView = new DataGridView();
        dataGridView.setCode(0);
        dataGridView.setMsg("");
        Map<Object,Object> map = new HashMap<>();
        //System.out.println(page.getTotal());
        map.put("count",orderVOS.size());
        map.put("page",page.getCurrent());
        map.put("zpage",page.getPages());
        map.put("list",orderVOS);
        dataGridView.setData(map);
        return dataGridView;
    }

    /**
     * 用户登录界面
     * @param userVO
     * @return
     */
    @RequestMapping("/login")
    public DataGridView loginUser(UserVO userVO,
                                  HttpServletRequest request){
        HttpSession session = request.getSession();
        /*//生成四位随机数
        String randomStr = RandomUtil.randomNumbers(6);
        //通过MD5工具类将六位随机数进行加密
        String md5Str = MD5Util.createMD5Str(randomStr);*/
        //将加密后的随机数保存到session域中
        String sessionId = session.getId();
        session.setAttribute("sessionId",sessionId);
        /*System.out.println(randomStr);
        System.out.println(md5Str);*/
        return new DataGridView(0,"登录成功",sessionId);
    }

    /**
     * 通过订单ID取消订单
     * @param orderId
     * @return
     */
    @PostMapping("/cancelOrderById")
    @Transactional
    public DataGridView cancelOrderById(Long orderId){
        Order order = orderService.getById(orderId);
        if (order == null){
            return new DataGridView(1,"该订单不存在","");
        }
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id",orderId);
        Order updateOrder = new Order();
        updateOrder.setOrderStatic(0);
        orderService.update(updateOrder,updateWrapper);
        return new DataGridView(0,"订单已取消","");
    }
}

